<?php

require_once PATH_AWS . '/sdk.class.php';

class ZFKiller_Amazon_SES {

	private $_emailBody;
	private $_emailBodyText;
	private $_emailFrom;
	private $_emailSubject;
	private $_emailTo = array();
	/**
	 *
	 * @var AmazonSES
	 */
	private $_amazonSesInstance;

	public function __construct(array $options = array()) {
		$options['sesOptions']['certificate_authority'] = PATH_AWS . '/lib/requestcore/cacert.pem';
		$this->_amazonSesInstance = new AmazonSES($options['sesOptions']);
	}

	public function addEmailTo($email, $name = null) {
		$this->_emailTo[] = $email;
	}

	public function addReplyTo($email, $name = '') {
		$this->_emailReplyTo[] = array('email' => $email, 'name' => $name);
	}

	public function clearReplyTo() {
		$this->_emailReplyTo = array();
	}

	public function setEmailBody($body) {
		$this->_emailBody = $body;
	}

	public function setEmailBodyText($body) {
		$this->_emailBodyText = $body;
	}

	public function setEmailFrom($email, $name = null) {
		$this->_emailFrom = array('email' => $email, 'name' => $name);
	}

	/**
	 * Define um assunto para o email
	 *
	 * @param string $subject 
	 */
	public function setEmailSubject($subject) {
		$this->_emailSubject = $subject;
	}

	/**
	 * Define um destinatario
	 * 
	 * @param string $to 
	 */
	public function setEmailTo($email, $name = null) {
		$this->_emailTo = array();
		$this->addEmailTo($email, $name);
	}

	/**
	 *
	 * @return boolean
	 */
	public function send() {
		$destination = array(
			'ToAddresses' => $this->_emailTo,
		);

		$message = array(
			'Subject' => array(
				'Data' => $this->_emailSubject,
			),
			'Body' => array()
		);

		if (null !== $this->_emailBodyText) {
			$message['Body']['Text'] = array(
				'Data' => $this->_emailBodyText,
			);
		}
		if (null !== $this->_emailBody) {
			$message['Body']['Html'] = array(
				'Data' => $this->_emailBody,
			);
		}
		
		$sender = "{$this->_emailFrom['name']}<{$this->_emailFrom['email']}>";
		
		$opt = array();
		if(isset($this->_emailReplyTo[0])){
			$opt['ReplyToAddresses'] = "{$this->_emailReplyTo[0]['name']}<{$this->_emailReplyTo[0]['email']}>";
		}

		$response = $this->_amazonSesInstance->send_email($sender, $destination, $message, $opt);
		return $response->isOK();
	}
}